package processor

import (
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"os"
)

// Quit 退出进程管理器
func (cls *Processor) Quit() error {
	cls.mutex.Lock()
	defer cls.mutex.Unlock()

	cls.quiting = true
	for _, application := range cls.application {
		if StateStarted != application.state {
			continue
		}

		application.quiting = true
		application.state = StateStopping
		application.callback(StateStopping, nil)

		logger.GetLogger().Sugar().Infof("进程管理器: 退出应用: %s...", application.name)
		if err := application.c.Process.Signal(os.Interrupt); nil != err {
			logger.GetLogger().Sugar().Errorf("进程管理器: 关闭应用失败: %s", err)
		}

		// 等待进程退出
		_ = application.c.Wait()
		logger.GetLogger().Sugar().Infof("进程管理器: 应用已退出: %s", application.name)

		application.state = StateStopped
		application.callback(StateStopped, nil)

		// 清理资源
		if err := application.output.Close(); nil != err {
			logger.GetLogger().Sugar().Errorf("进程管理器: 关闭应用输出文件失败，%s", err)
		}
	}

	return nil
}
